import requests
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QDialog, QVBoxLayout, QFrame, QLabel, QLineEdit, QHBoxLayout, QRadioButton, QPushButton, \
    QMessageBox, QButtonGroup, QTextEdit
from PyQt5.QtGui import QPixmap, QIcon
import re

class AdminAuthDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("管理员身份验证")
        self.setFixedSize(400, 200)
        self.setWindowIcon(QIcon('./images/购物.png'))
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)

        # 提示标签
        label = QLabel("请输入管理员验证密码：")
        label.setStyleSheet("""
            color: #2c3e50;
            font-weight: bold;
            font-size: 16px;
            padding: 5px 0;
        """)
        layout.addWidget(label)

        # 密码输入框
        self.password_input = QTextEdit(self)

        self.password_input.setPlaceholderText("请输入密码")
        self.password_input.setFixedHeight(36)  # 固定高度以模拟单行输入
        self.password_input.setAcceptRichText(False)  # 禁用富文本
        self.password_input.setStyleSheet("""
            QTextEdit {
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                padding: 10px;  /* 增加内边距以防止文字被遮挡 */
                font-size: 16px;
                background-color: #fafafa;
                color: #2c3e50;
                min-width: 300px;
                line-height: 1.2;
            }
            QTextEdit:focus {
                border-color: #3498db;
                background-color: white;
            }
            QTextEdit:hover {
                border-color: #bdc3c7;
            }
        """)
        # 限制为单行输入
        self.password_input.textChanged.connect(self.restrict_to_single_line)
        layout.addWidget(self.password_input)

        # 按钮布局
        button_layout = QHBoxLayout()
        confirm_button = QPushButton("确认")
        confirm_button.setCursor(Qt.PointingHandCursor)
        confirm_button.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
                color: white;
                border: none;
                font-size: 16px;
                font-weight: bold;
                padding: 10px;
                min-width: 100px;
                min-height: 32px;  /* 缩小高度 */
                border-radius: 15px;  /* 增加圆角 */
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
            }
            QPushButton:pressed {
                color: #ccc;
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
            }
        """)
        confirm_button.clicked.connect(self.verify_password)
        button_layout.addWidget(confirm_button)

        layout.addLayout(button_layout)
        layout.addStretch()

    def restrict_to_single_line(self):
        # 限制 QTextEdit 为单行输入
        text = self.password_input.toPlainText()
        if '\n' in text:
            self.password_input.setPlainText(text.replace('\n', ''))
            cursor = self.password_input.textCursor()
            cursor.movePosition(cursor.End)
            self.password_input.setTextCursor(cursor)

    def verify_password(self):
        password = self.password_input.toPlainText()
        if password == "我是马云":
            self.accept()
        else:
            QMessageBox.warning(self, "错误", "管理员密码错误，请重新输入")
            self.password_input.clear()

class RegisterDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        # 设置窗口图标
        icon = QIcon('./images/购物.png')
        self.setWindowIcon(icon)
        self.setWindowTitle("注册")
        self.setFixedSize(500, 500)  # 合理窗口尺寸
        self.ui_init()

    def ui_init(self):
        self.mainLayout = QVBoxLayout(self)
        self.mainContainer = QFrame(self)
        self.mainLayout.addWidget(self.mainContainer)

        self.containerLayout = QVBoxLayout(self.mainContainer)

        self.headerLayout = QHBoxLayout()
        self.formLayout = QVBoxLayout()
        self.buttonLayout = QVBoxLayout()

        self.containerLayout.addLayout(self.headerLayout)
        self.containerLayout.addLayout(self.formLayout)
        self.containerLayout.addLayout(self.buttonLayout)
        self.containerLayout.setSpacing(10)

        # 标题和图标
        self.logoLabel = QLabel()
        self.logoLabel.setFixedSize(80, 80)
        self.logoLabel.setPixmap(QPixmap('./images/购物1.png'))
        self.logoLabel.setScaledContents(True)

        self.titleLabel = QLabel("用户注册")
        self.titleLabel.setStyleSheet("font-family: 黑体; font-size: 28px; font-weight: bold; color: #2c3e50;")
        self.headerLayout.addWidget(self.logoLabel)
        self.headerLayout.addWidget(self.titleLabel)
        self.headerLayout.addStretch()
        self.headerLayout.setAlignment(Qt.AlignLeft)

        # 输入框和标签样式
        inputStyleSheet = """
            QLineEdit {
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                padding: 8px;
                font-size: 16px;
                background-color: #fafafa;
                color: #2c3e50;
                min-width: 300px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: white;
            }
            QLineEdit:hover {
                border-color: #bdc3c7;
            }
        """
        labelStyleSheet = """
            color: #2c3e50;
            font-weight: bold;
            font-size: 16px;
            padding: 5px 0;
            min-width: 80px;
        """

        # 输入字段和标签
        self.usernameLabel = QLabel("用户名")
        self.usernameLabel.setStyleSheet(labelStyleSheet)
        self.usernameInput = QLineEdit(self)
        self.usernameInput.setPlaceholderText("请输入用户名")
        self.usernameInput.setStyleSheet(inputStyleSheet)
        self.usernameLayout = QHBoxLayout()
        self.usernameLayout.addWidget(self.usernameLabel)
        self.usernameLayout.addWidget(self.usernameInput)
        self.usernameLayout.addStretch()

        self.emailLabel = QLabel("邮箱")
        self.emailLabel.setStyleSheet(labelStyleSheet)
        self.emailInput = QLineEdit(self)
        self.emailInput.setPlaceholderText("请输入邮箱地址")
        self.emailInput.setStyleSheet(inputStyleSheet)
        self.emailLayout = QHBoxLayout()
        self.emailLayout.addWidget(self.emailLabel)
        self.emailLayout.addWidget(self.emailInput)
        self.emailLayout.addStretch()

        self.passwordLabel = QLabel("密码")
        self.passwordLabel.setStyleSheet(labelStyleSheet)
        self.passwordInput = QLineEdit(self)
        self.passwordInput.setPlaceholderText("请输入密码")
        self.passwordInput.setEchoMode(QLineEdit.Password)
        self.passwordInput.setStyleSheet(inputStyleSheet)
        self.passwordLayout = QHBoxLayout()
        self.passwordLayout.addWidget(self.passwordLabel)
        self.passwordLayout.addWidget(self.passwordInput)
        self.passwordLayout.addStretch()

        self.confirmLabel = QLabel("确认密码")
        self.confirmLabel.setStyleSheet(labelStyleSheet)
        self.confirmInput = QLineEdit(self)
        self.confirmInput.setPlaceholderText("请输入确认密码")
        self.confirmInput.setEchoMode(QLineEdit.Password)
        self.confirmInput.setStyleSheet(inputStyleSheet)
        self.confirmLayout = QHBoxLayout()
        self.confirmLayout.addWidget(self.confirmLabel)
        self.confirmLayout.addWidget(self.confirmInput)
        self.confirmLayout.addStretch()

        self.roleLabel = QLabel("账户类型")
        self.roleLabel.setStyleSheet(labelStyleSheet)
        self.roleContainer = QFrame(self)
        self.roleLayout = QHBoxLayout(self.roleContainer)
        self.userRadio = QRadioButton("🛒 普通用户")
        self.userRadio.setChecked(True)
        self.adminRadio = QRadioButton("👨 管理员")
        self.roleLayout.addWidget(self.userRadio)
        self.roleLayout.addWidget(self.adminRadio)
        self.roleLayout.addStretch()
        self.role_group = QButtonGroup()
        self.role_group.addButton(self.userRadio, 0)
        self.role_group.addButton(self.adminRadio, 1)

        # 添加到表单布局
        self.formLayout.addLayout(self.usernameLayout)
        self.formLayout.addLayout(self.emailLayout)
        self.formLayout.addLayout(self.passwordLayout)
        self.formLayout.addLayout(self.confirmLayout)
        self.formLayout.addWidget(self.roleLabel)
        self.formLayout.addWidget(self.roleContainer)
        self.formLayout.setSpacing(10)

        # 按钮
        self.registerButton = QPushButton("注册")
        self.registerButton.setCursor(Qt.PointingHandCursor)
        self.registerButton.setStyleSheet("""
            QPushButton {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
                color: white;
                border: none;
                font-size: 16px;
                font-weight: bold;
                padding: 10px;
                min-width: 300px;
                min-height: 32px;  /* 缩小高度 */
                border-radius: 15px;  /* 增加圆角 */
            }
            QPushButton:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
            }
            QPushButton:pressed {
                color: #ccc;
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ff9500, stop:1 #ff5100);
            }
            QPushButton:disabled {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #ffcc7f, stop:1 #ffa87f);
                color: white;
                border: none;
                font-size: 16px;
                font-weight: bold;
                padding: 10px;
                min-width: 300px;
                min-height: 32px;  /* 缩小高度 */
                border-radius: 15px;  /* 增加圆角 */
            }
        """)
        self.registerButton.clicked.connect(self.register)
        self.confirmInput.returnPressed.connect(self.registerButton.click)

        self.buttonLayout.addWidget(self.registerButton)
        self.buttonLayout.setSpacing(10)
        self.buttonLayout.setAlignment(Qt.AlignHCenter)

        # 连接 textChanged 信号以更新按钮状态
        self.usernameInput.textChanged.connect(self.update_button_state)
        self.emailInput.textChanged.connect(self.update_button_state)
        self.passwordInput.textChanged.connect(self.update_button_state)
        self.confirmInput.textChanged.connect(self.update_button_state)

        # 初始化按钮状态
        self.update_button_state()

    def update_button_state(self):
        username = self.usernameInput.text()
        email = self.emailInput.text()
        password = self.passwordInput.text()
        confirm = self.confirmInput.text()

        # 验证每行输入是否包含至少1个数字
        valid = True
        if not re.search(r'\d', username):
            valid = False
        if not re.search(r'\d', email):
            valid = False
        if not re.search(r'\d', password):
            valid = False
        if not re.search(r'\d', confirm):
            valid = False

        self.registerButton.setEnabled(valid)

    def register(self):
        inputStyleSheet = """
            QLineEdit {
                border: 2px solid red;
                border-radius: 10px;
                padding: 8px;
                font-size: 16px;
                background-color: #fafafa;
                color: #2c3e50;
                min-width: 300px;
            }
        """
        normalStyleSheet = """
            QLineEdit {
                border: 2px solid #e0e0e0;
                border-radius: 10px;
                padding: 8px;
                font-size: 16px;
                background-color: #fafafa;
                color: #2c3e50;
                min-width: 300px;
            }
            QLineEdit:focus {
                border-color: #3498db;
                background-color: white;
            }
            QLineEdit:hover {
                border-color: #bdc3c7;
            }
        """
        username = self.usernameInput.text()
        email = self.emailInput.text()
        password = self.passwordInput.text()
        confirm = self.confirmInput.text()

        # 重置输入框样式
        self.usernameInput.setStyleSheet(normalStyleSheet)
        self.emailInput.setStyleSheet(normalStyleSheet)
        self.passwordInput.setStyleSheet(normalStyleSheet)
        self.confirmInput.setStyleSheet(normalStyleSheet)

        # 输入验证：每行必须包含至少1个数字
        valid = True
        error_messages = []

        if not re.search(r'\d', username):
            self.usernameInput.setStyleSheet(inputStyleSheet)
            error_messages.append("用户名必须包含至少1个数字")
            valid = False

        if not re.search(r'\d', email):
            self.emailInput.setStyleSheet(inputStyleSheet)
            error_messages.append("邮箱必须包含至少1个数字")
            valid = False

        if not re.search(r'\d', password):
            self.passwordInput.setStyleSheet(inputStyleSheet)
            error_messages.append("密码必须包含至少1个数字")
            valid = False

        if not re.search(r'\d', confirm):
            self.confirmInput.setStyleSheet(inputStyleSheet)
            error_messages.append("确认密码必须包含至少1个数字")
            valid = False

        if not valid:
            QMessageBox.warning(self, "注册错误", "\n".join(error_messages))
            return

        # 管理员身份验证
        is_admin = self.role_group.checkedId()  # 0=普通用户, 1=管理员
        if is_admin == 1:
            admin_dialog = AdminAuthDialog(self)
            if not admin_dialog.exec_():
                return  # 用户取消或密码错误，直接返回

        try:
            data = {
                "username": username,
                "email": email,
                "password": password,
                "is_admin": is_admin
            }
            base_url = "http://127.0.0.1:8000/api/auth/register"
            response = requests.post(base_url, json=data)

            if response.status_code == 200:
                user_info = response.json()
                print("注册成功！", user_info)
                QMessageBox.information(self, "成功", "注册成功")
                self.accept()
            else:
                error_info = response.json()
                print(f"注册失败：{error_info.get('detail', '未知错误')}")
                QMessageBox.information(self, "失败", "注册失败")
        except Exception as e:
            QMessageBox.warning(self, "错误", f"发生未知错误: {e}")

    def accept(self):
        super().accept()

if __name__ == '__main__':
    from PyQt5.QtWidgets import QApplication
    import sys
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
    app = QApplication(sys.argv)
    dialog = RegisterDialog()
    dialog.show()
    sys.exit(app.exec_())